package web

import (
	"commerce/cache"
	"commerce/common"
	"commerce/data"
	"commerce/model"
	"commerce/req"
	"commerce/vo"
	"encoding/json"
	"fmt"
	"net/http"
)

// @ todo 千万别。。。
const (
	appId  = "wxd51ae4e7c02ca594"
	secret = "456bbfef2193dc7c19177651b96c5145"
)

func AuthByWx(w http.ResponseWriter, r *http.Request) {

	var authReq req.AuthReq
	err := json.NewDecoder(r.Body).Decode(&authReq)

	if err != nil {
		common.Error.Printf("AuthByWx err:%v", err)
		j, _ := json.Marshal(vo.Err(err.Error()))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	session, err := codeToSession(appId, secret, authReq.Code)
	if err != nil || session.ErrCode != 0 {
		common.Error.Printf("2.AuthByWx err:%v, session:%v", err, session)
		var errMsg string
		if err != nil {
			errMsg = err.Error()
		} else {
			errMsg = session.ErrMsg
		}
		j, _ := json.Marshal(vo.Err(errMsg))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	member, err := data.GetMemberByWxInfo(session.OpenId)
	if err != nil {
		common.Error.Printf("3.AuthByWx err:%v", err)
		j, _ := json.Marshal(vo.Err(err.Error()))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	info := authReq.UserInfo.UserInfo
	var memberId int
	// 注册过
	if member != nil {
		// 更新用户信息
		err = data.UpdateMemberById(member.Id, info)
		if err != nil {
			common.Error.Println("UpdateMemberById err:", err)
		}
		memberId = member.Id
	} else {
		// 新用户
		memberId, err = data.AddMember(model.Member{NickName: info.NickName, Avatar: info.AvatarUrl, Gender: info.Gender,
			OpenId: session.OpenId, SessionKey: session.SessionKey, Country: info.Country,
			Province: info.Province, City: info.City, Status: 1})
		if err != nil {
			common.Error.Printf("4.AuthByWx err:%v", err)
			j, _ := json.Marshal(vo.Err("系统繁忙，请稍候再试！"))
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusOK)
			w.Write(j)
			return
		}
	}
	token, err := generateAppJWT(memberId, info.NickName)
	if err != nil {
		common.Error.Printf("5.AuthByWx err:%v", err)
		j, _ := json.Marshal(vo.Err("系统繁忙，请稍候再试！"))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	var res vo.AuthVo
	res.UserId = memberId
	res.UserInfo = vo.MemberVo{UserId: memberId, Nickname: info.NickName, Avatar: info.AvatarUrl}
	res.Token = token

	err = cache.SetWithTTL(fmt.Sprintf("%s:%d", "Member", memberId), token, common.APP_TOKEN_AGE*3600)
	if err != nil {
		common.Error.Printf("6.AuthByWx err:%v", err)
		j, _ := json.Marshal(vo.Err("系统繁忙，请稍候再试！"))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	j, _ := json.Marshal(vo.Ok(res))
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write(j)
}
